import { ConfigEnv, UserConfig } from 'vite';
import path from 'path';
import vue from '@vitejs/plugin-vue';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';

function pathResolve(dir: string) {
	return path.join(__dirname, dir);
}

function computedPlugins(mode) {
	const plugins = [
		vue(),
		// 自动导入
		AutoImport({
			imports: ['vue'],
		}),
	];
	if (mode && mode === 'production') {
		plugins.push(Components({ resolvers: [VantResolver({})] }));
	}
	return plugins;
}

export default ({ command, mode }: ConfigEnv): UserConfig => {
	return {
		optimizeDeps: {
			include: ['@vue/shared'],
		},
		base: './',
		build: {
			outDir: path.resolve(__dirname, 'dist'),
		},
		plugins: computedPlugins(mode),
		resolve: {
			alias: [
				{
					find: /@\//,
					replacement: pathResolve('src') + '/',
				},
				// /#/xxxx => types/xxxx
				{
					find: /@components\//,
					replacement: pathResolve('src') + '/components/',
				},
				{
					find: /@views\//,
					replacement: pathResolve('src') + '/views/',
				},
				{
					find: /@widgets\//,
					replacement: pathResolve('src') + '/widgets/',
				},
				{
					find: /@plugins\//,
					replacement: pathResolve('src') + '/plugins/',
				},
			],
		},
		server: {
			port: 8999,
			proxy: {
				'/cloudehr__ibizehrapp': {
					target: 'http://172.16.240.140:20086/',
				},
				'/examplesys__web': {
					target: 'http://172.16.88.5:20086/',
				},
				'/api2': {
					target: 'http://localhost:8080/',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api2/, ''),
				},
				'/api': {
					target: 'http://172.16.240.110:51001/',
					changeOrigin: true,
					rewrite: (path) => path.replace(/^\/api/, ''),
				},
			},
		},
	};
};
